document.addEventListener('DOMContentLoaded', function() {
    const baseURL = 'http://127.0.0.1:5000'; // 本地代理的Flask服务器
    const recommendList = document.getElementById('recommendList');
    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');
    const categories = document.querySelectorAll('.category');
    let currentCategory = '0';
    let currentIndex = 0;
    let playlists = [];
    let mouseOverList = false; // 标志位，判断鼠标是否在推荐列表区域

    function fetchRecommendPlaylists(categoryId) {
        let url = `${baseURL}/recommend/playlist/u`;
        if (categoryId !== '0') {
            url = `${baseURL}/recommend/playlist?id=${categoryId}`;
        }

        fetch(url)
            .then(response => response.json())
            .then(data => {
                console.log('Received data:', data);
                if (data.result === 100 || data.data) {
                    playlists = data.list || data.data.list;
                    displayPlaylists();
                } else {
                    throw new Error('Invalid data format');
                }
            })
            .catch(error => console.error('Error fetching recommend playlist:', error));
    }

    function displayPlaylists() {
        recommendList.innerHTML = '';
        const start = currentIndex * 4;
        const end = start + 4;
        const currentPlaylists = playlists.slice(start, end);

        currentPlaylists.forEach(playlist => {
            const playlistItem = document.createElement('div');
            playlistItem.classList.add('recommend-item');
            playlistItem.innerHTML = `
                <img src="${playlist.cover_url_small || playlist.cover}" alt="Playlist Image">
                <p>${playlist.title}</p>
            `;
            playlistItem.addEventListener('dblclick', () => {
                window.open(`/playlist_detail?playlist_id=${playlist.tid || playlist.content_id}`, '_blank');
            });
            recommendList.appendChild(playlistItem);
        });

        updateNavigationButtons();
    }

    function updateNavigationButtons() {
        prevBtn.style.display = currentIndex === 0 ? 'none' : 'block';
        nextBtn.style.display = (currentIndex + 1) * 4 >= playlists.length ? 'none' : 'block';
    }

    categories.forEach(category => {
        category.addEventListener('click', function() {
            categories.forEach(cat => cat.classList.remove('active'));
            this.classList.add('active');
            currentCategory = this.dataset.id;
            currentIndex = 0;
            fetchRecommendPlaylists(currentCategory);
        });
    });

    prevBtn.addEventListener('click', () => {
        if (currentIndex > 0) {
            currentIndex--;
            displayPlaylists();
        }
    });

    nextBtn.addEventListener('click', () => {
        if ((currentIndex + 1) * 4 < playlists.length) {
            currentIndex++;
            displayPlaylists();
        }
    });

    recommendList.addEventListener('mouseover', () => {
        mouseOverList = true;
        prevBtn.style.display = currentIndex === 0 ? 'none' : 'block';
        nextBtn.style.display = (currentIndex + 1) * 4 >= playlists.length ? 'none' : 'block';
    });

    recommendList.addEventListener('mouseout', () => {
        mouseOverList = false;
        setTimeout(() => {
            if (!mouseOverList) {
                prevBtn.style.display = 'none';
                nextBtn.style.display = 'none';
            }
        }, 200);
    });

    prevBtn.addEventListener('mouseover', () => {
        mouseOverList = true;
    });

    prevBtn.addEventListener('mouseout', () => {
        mouseOverList = false;
        setTimeout(() => {
            if (!mouseOverList) {
                prevBtn.style.display = 'none';
                nextBtn.style.display = 'none';
            }
        }, 200);
    });

    nextBtn.addEventListener('mouseover', () => {
        mouseOverList = true;
    });

    nextBtn.addEventListener('mouseout', () => {
        mouseOverList = false;
        setTimeout(() => {
            if (!mouseOverList) {
                prevBtn.style.display = 'none';
                nextBtn.style.display = 'none';
            }
        }, 200);
    });

    fetchRecommendPlaylists(currentCategory);
});
